package com.fit.pages.user;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.PropertyAccess;
import org.apache.tapestry5.util.EnumSelectModel;

import com.fit.annotations.AdminAccess;
import com.fit.dao.employee.EmployeeDAO;
import com.fit.dao.user.UserDAO;
import com.fit.entities.Employee;
import com.fit.entities.User;
import com.fit.model.glov.GenericSelectModel;
import com.fit.model.user.MD5;
import com.fit.model.user.Type;
import com.fit.pages.ErrorPage;

@AdminAccess
public class CreateUser {

	@Property
	private User user;

	@InjectPage
	private ErrorPage errorPage;

	@Inject
	private UserDAO userDAO;

	@Inject
	private Messages messages;

	@Persist
	private String msg;

	@Inject
	private PropertyAccess access;

	@Property
	private Employee employee;

	@Inject
	private EmployeeDAO employeeDAO;

	@Property
	@Persist
	private Type type;

	private GenericSelectModel<Employee> employees; // lista koja ce da se
													// prikaza u cb

	public String getMsg() {
		return msg;
	}

	public GenericSelectModel<Employee> getEmployees() {
		employees = new GenericSelectModel<Employee>(employeeDAO.findAll(),
				Employee.class, "name", "jmbg", access);
		return employees;
	}

	public SelectModel getTypes() {
		return new EnumSelectModel(Type.class, messages);
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	Object onSuccess() {
		errorPage.setMessage("");
		if (type == null) {
			msg = "You didn't choose type!";
			return null;
		}
		user.setType(type.toString());
		user.setEmployee(employee);
		user.setPassword(MD5.md5(user.getPassword()));
		if (userDAO.save(user)) {
			errorPage.setMessage("User successfully added!");
			return errorPage;
		}
		errorPage.setMessage("User is null!");
		return errorPage;

	}

}
